package com.cby.operation.samples

import android.content.SharedPreferences
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.appcompat.app.AppCompatActivity
import com.cby.operation.initialize.InitListener
import com.cby.operation.login.LoginListener
import com.cby.operation.login.OperationSDK
import com.cby.operation.login.UserInfo
import com.cby.operation.pay.PayListener
import com.cby.operation.pay.PlatformSDK
import com.cby.operation.pay.bean.PayInfo
import com.m3839.sdk.demo.isNumeric
import java.util.*

class MainActivity : AppCompatActivity() {

    private val gameId = "12389"

    private val mainHandler = Handler(Looper.getMainLooper())

    private var moneyEdit: EditText? = null
    private var goodsNameEdit: EditText? = null

    //private TextView userNameTv;
    private var gameIdEdit: EditText? = null

    private var orientationSp: Spinner? = null

    private var mSp: SharedPreferences? = null

    private val orientations = arrayOf(
        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,  // 1，竖屏
        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE // 0，横屏
    )

    private val orientationsNames = arrayOf(
        "竖屏",
        "横屏"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        mSp = getSharedPreferences("sdk_sp", MODE_PRIVATE)

        // 设置Activity的方向
        setDemoOrientation()

        setContentView(R.layout.activity_main)

        moneyEdit = findViewById(R.id.et_money)
        gameIdEdit = findViewById(R.id.et_game_id)
        orientationSp = findViewById(R.id.spinner_orientation)
        goodsNameEdit = findViewById(R.id.et_goodsname)
        gameIdEdit!!.setText(gameId)

        initOrientationSpinner()
    }

    fun onInitClick(view: View?) {
        if (gameIdEdit!!.length() <= 0) {
            showToast("游戏ID不能为空")
            return
        }
        if (!isNumeric(gameIdEdit!!.text.toString().trim { it <= ' ' })) {
            showToast("游戏ID只能为正整数")
            return
        }
        if (gameIdEdit!!.length() > 6) {
            showToast("游戏ID只能为正整数")
            return
        }
        OperationSDK.initSdk(
            this@MainActivity,
            gameIdEdit!!.text.toString().trim { it <= ' ' },
            getOrientation(),
            object : InitListener {

                override fun onInitSuccess() {
                    showToast("初始化成功")
                }

                override fun onInitFailed(code: Int, message: String?) {
                    showToast("code = $code, message = $message")
                }
            })
    }


    fun onLoginClick(view: View?) {
        OperationSDK.login(this@MainActivity, false, loginListener)
    }

    private val loginListener = object : LoginListener {

        override fun onLoginSuccess(userInfo: UserInfo) {
            showToast("登录成功 user = ${userInfo.toString()}")
        }

        override fun onLoginFailed(code: Int, msg: String?) {
            showToast("code = $code, message = $msg")
            if (code == 2005) {
                finish()
            }
        }

    }

    fun onLogoutClick(view: View?) {
        OperationSDK.logout(this@MainActivity)
    }

    fun onRechargeClick(view: View?) {
        if (moneyEdit!!.length() <= 0) {
            showToast("金额不能为空")
            return
        }
        if (!isNumeric(moneyEdit!!.text.toString())) {
            showToast("金额只能为整数")
            return
        }
        if (goodsNameEdit!!.length() <= 0) {
            showToast("商品名称不能为空")
            return
        }
        val money = moneyEdit!!.text.toString()
        val goodsName = goodsNameEdit!!.text.toString()
        if (money.length > 6) {
            showToast("最大金额不允许超过5万")
            return
        }
        val moneyInt = money.toInt()
        if (moneyInt > 50000) {
            showToast("最大金额不允许超过5万")
            return
        }
        if (moneyInt <= 0) {
            showToast("金额必须大于0")
            return
        }

        //测试数据
        val payInfo = PayInfo()
        val r = Random()
        payInfo.cpOrderId = "CXZ258654" + r.nextInt(1000)
        payInfo.money = moneyInt
        payInfo.goodsName = goodsName
        payInfo.server = 1
        PlatformSDK.pay(this, payInfo) { code, message, pInfo ->
            if (code == 9000) {
                showToast("支付成功，进行商品发放")
            } else if (code == 2005) {
                finish()
            } else {
                showToast(message!!)
            }
        }

    }

    fun onSwitchUserClick(view: View?) {
        OperationSDK.login(this@MainActivity, true, loginListener)
    }

    fun onUserStateClick(view: View?) {
        showToast(OperationSDK.getUser().toString())
    }

    /**
     * 测试SDK界面的方向设置
     *
     * 为了在Demo中测试横竖屏，提供Spinner控件设置方向配置，并保持着SharedPreference中
     * 实际接入直接设置OperateCenterConfig
     * .Builder(this)。setOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
     *
     * 注意：横竖屏设置都需要重启Demo才能生效; 测试旋转屏幕时要开启“自动旋转屏幕”
     */
    private fun setDemoOrientation() {
        val ori = getOrientation()
        requestedOrientation = ori
    }

    private fun initOrientationSpinner() {
        val adapter: ArrayAdapter<String> = ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            orientationsNames
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        orientationSp!!.adapter = adapter
        orientationSp!!.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, pos: Int, id: Long) {
                Log.d("m3839", "Set orientation as " + orientationsNames[pos])
                saveOrientation(pos)
            }

            override fun onNothingSelected(arg0: AdapterView<*>?) {}
        }

        // 这里设置默认方向为横屏，SDK内部的默认方向也是
        orientationSp!!.setSelection(mSp!!.getInt("orientation", 0))
    }

    private fun saveOrientation(pos: Int) {
        mSp!!.edit().putInt("orientation", pos).apply()
    }

    private fun getOrientation(): Int {
        var pos = mSp!!.getInt("orientation", 0)
        if (pos < 0 || pos > 3) pos = 0
        return orientations[pos]
    }

    override fun onDestroy() {
        OperationSDK.releaseSDK()
        super.onDestroy()
    }

    private fun showToast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }
}